package com.lyc.service.impl;

import com.lyc.constant.Constant;
import com.lyc.dao.CategoryMapper;
import com.lyc.dao.ProductMapper;
import com.lyc.entity.Category;
import com.lyc.entity.Product;
import com.lyc.entity.vo.PageBean;
import com.lyc.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.List;

@Service
@Transactional
public class CategoryServiceImpl implements ICategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private ProductMapper productMapper;

    @Override
    public List<Category> getAll() {
        return categoryMapper.selectAll();
    }

    @Override
    public Category getCategoryByCid(Integer cid) {
        return categoryMapper.selectByPrimaryKey(cid);
    }

    @Override
    public void addCategory(Category category) {
        categoryMapper.insertSelective(category);
    }

    @Override
    public void updateCategory(Category category) {
        categoryMapper.updateByPrimaryKeySelective(category);
    }

    @Override
    public PageBean<Category> getAllByPage(Integer currentPage) {
        PageBean<Category> pageBean = new PageBean<>();
        pageBean.setCurrentPage(currentPage);
        pageBean.setPageSize(Constant.CATEGORY_PAGE_SIZE);
        pageBean.setTotalCount(categoryMapper.selectAllCount());
        pageBean.setStart((currentPage-1)*pageBean.getPageSize());
        pageBean.setTotalPage((int) Math.ceil((double)(pageBean.getTotalCount())/pageBean.getPageSize()));
        List<Category> categories = categoryMapper.selectByPage(pageBean.getStart(),pageBean.getPageSize());
        pageBean.setData(categories);
        return pageBean;
    }

    @Override
    public void deleteCategoryByCid(Integer cid) {
        //删除该分类下的所有商品
        List<Product> productList = productMapper.selectByCid(cid);
        for (Product product:productList){
            productMapper.deleteByPrimaryKey(product.getPid());
        }
        categoryMapper.deleteByPrimaryKey(cid);
    }
}
